# 用"*"打印中文名字的Python程序

# 导入必要的库
from PIL import Image, ImageDraw, ImageFont
import os
import sys
import platform

# 这里定义一些常见汉字的点阵数据（16x16）作为后备
# 格式：每个汉字由16个字符串组成，每个字符串代表一行的点阵
chinese_chars = {
    # 优化的点阵字符
    '张': [
        "***     ***     ",
        "***     ***     ",
        "***     ***     ",
        "***     ***     ",
        "******  ***     ",
        "*** *** ***     ",
        "*** *** ***     ",
        "*** *** ***     ",
        "*** *** ***     ",
        "*** *** ***     ",
        "*** *** ******  ",
        "*** *** *******",
        "*** *** *** *** ",
        "*** *** *** *** ",
        "*** *** *** *** ",
        "*** *** *** *** "
    ],
    '王': [
        "   ******      ",
        "   *** ***     ",
        "   *** ***     ",
        "   *** ***     ",
        "   *** ***     ",
        "**************",
        "**************",
        "   *** ***     ",
        "   *** ***     ",
        "   *** ***     ",
        "   *** ***     ",
        "   *** ***     ",
        "   *** ***     ",
        "   *** ***     ",
        "   *** ***     ",
        "   *** ***     "
    ],
    '李': [
        "******         ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "******         ",
        "***            ",
        "***            ",
        "***            ",
        "**************",
        "***            ",
        "***            ",
        "***            ",
        "***            ",
        "***            ",
        "***            ",
        "***            "
    ],
    '赵': [
        " ******        ",
        "********       ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      "
    ],
    '刘': [
        "   ******      ",
        "   ***   ***    ",
        "   ***   ***    ",
        "   ***   ***    ",
        "   ***   ***    ",
        "   ******      ",
        "   ***         ",
        "   ***         ",
        "   ***         ",
        "   ***         ",
        "   ***         ",
        "   ***         ",
        "   ***         ",
        "   ***         ",
        "   ***         ",
        "   ***         "
    ],
    '陈': [
        "***            ",
        "***            ",
        "***            ",
        "***            ",
        "***            ",
        "***            ",
        "***            ",
        "***            ",
        "******         ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "***   ***      ",
        "******         ",
        "***            "
    ],
    # 添加更多常用字符
    '明': [
        "******  ****** ",
        "*** *** *** ***",
        "*** *** *** ***",
        "*** *** *** ***",
        "*** *** *** ***",
        "******  ****** ",
        "***            ",
        "***            ",
        "******  ****** ",
        "***  *** *** ***",
        "***  *** *** ***",
        "***  *** *** ***",
        "***  *** *** ***",
        "******  ****** ",
        "                ",
        "                "
    ],
    '红': [
        "***      ******",
        "***     ***  ***",
        "***     ***  ***",
        "***     ***  ***",
        "***      ****** ",
        "***             ",
        "***    ******   ",
        "***   *** ***   ",
        "***   *** ***   ",
        "***   *** ***   ",
        "***   *** ***   ",
        "***    ******   ",
        "***             ",
        "***             ",
        "***             ",
        "***             "
    ]
}

# 为了简化，我们使用'?'作为未定义字符的占位符
question_mark = [
    "                ",
    "                ",
    "    ****        ",
    "    ****        ",
    "    ****        ",
    "    ****        ",
    "    ****        ",
    "    ****        ",
    "                ",
    "                ",
    "                ",
    "    ****        ",
    "                ",
    "                ",
    "                ",
    "                "
]

def get_font_path():
    """
    简化的字体获取函数，专注于找到最适合点阵显示的Windows中文字体
    """
    # 针对Windows系统，直接检查几个最常用且效果最好的字体
    windows_fonts = [
        'C:\\Windows\\Fonts\\simhei.ttf',  # 黑体，最适合点阵显示
        'C:\\Windows\\Fonts\\simhei.ttc',
        'C:\\Windows\\Fonts\\msyh.ttc',   # 微软雅黑
        'C:\\Windows\\Fonts\\simsun.ttc',  # 宋体
        'C:\\Windows\\Fonts\\simkai.ttf',  # 楷体
    ]
    
    # 检查Windows字体
    for font_path in windows_fonts:
        if os.path.exists(font_path):
            return font_path
    
    # 如果是Windows系统但没找到字体，尝试通用路径
    if platform.system() == 'Windows':
        font_dir = 'C:\\Windows\\Fonts'
        if os.path.exists(font_dir):
            # 遍历字体目录，寻找中文字体
            for file in os.listdir(font_dir):
                # 优先考虑黑体，因为它在点阵显示中效果最好
                if ('hei' in file.lower() or 'black' in file.lower()) and \
                   (file.endswith('.ttf') or file.endswith('.ttc')):
                    return os.path.join(font_dir, file)
    
    # 如果找不到中文字体，返回None
    return None

def char_to_matrix(char, size=16, style='*'):
    """
    全新设计的字符转点阵函数，采用直接渲染方法确保清晰的中文字符显示
    
    参数:
        char: 要转换的字符
        size: 点阵大小 (默认16x16)
        style: 显示样式字符 (默认'*')
    
    返回:
        包含点阵数据的列表，每个元素是一个字符串
    """
    # 首先检查是否有内置的点阵数据，优先使用
    if char in chinese_chars and size == 16:
        return chinese_chars[char]
    
    try:
        # 创建一个与目标点阵大小完全匹配的图像
        img = Image.new('1', (size, size), 1)  # 1表示1位像素模式，1为白色
        draw = ImageDraw.Draw(img)
        
        # 尝试获取中文字体
        font_path = get_font_path()
        
        # 关键改进：使用更大的字体大小，然后通过不同的渲染方式确保清晰度
        if font_path:
            try:
                # 使用比点阵稍大的字体，然后通过抗锯齿和像素调整来确保清晰度
                font_size = size + 4
                font = ImageFont.truetype(font_path, font_size)
            except:
                # 如果无法加载指定字体，使用默认字体并调整策略
                font = ImageFont.load_default()
                font_size = size
        else:
            # 如果没有中文字体，使用默认字体并尝试渲染
            font = ImageFont.load_default()
            font_size = size
        
        # 使用textbbox获取文本边界框（如果可用）
        try:
            # 尝试获取文本边界
            bbox = draw.textbbox((0, 0), char, font=font)
            text_width = bbox[2] - bbox[0]
            text_height = bbox[3] - bbox[1]
        except (AttributeError, TypeError):
            # 如果无法获取边界框，使用字体大小估算
            text_width = size
            text_height = size
        
        # 计算居中位置
        x = (size - text_width) // 2
        y = (size - text_height) // 2 - 2  # 稍微向上调整，避免字符下沉
        
        # 确保位置合理
        x = max(0, x)
        y = max(0, y)
        
        # 绘制字符，使用黑色
        draw.text((x, y), char, font=font, fill=0)  # 0为黑色
        
        # 直接转换为点阵数据
        matrix = []
        for y in range(size):
            line = ""
            for x in range(size):
                # 在1位模式下，0表示黑色（字符），1表示白色（背景）
                if img.getpixel((x, y)) == 0:
                    line += style
                else:
                    line += ' '
            matrix.append(line)
        
        # 优化：清理多余的空白行和列，让字符更紧凑
        matrix = cleanup_matrix(matrix)
        
        return matrix
    except Exception as e:
        # 如果所有方法都失败，使用备用点阵
        return create_fallback_matrix(char, size, style)

def cleanup_matrix(matrix):
    """
    清理点阵矩阵，移除不必要的空白边缘
    """
    size = len(matrix)
    if size == 0:
        return matrix
    
    # 找到包含字符的最小边界
    min_row, max_row = size, -1
    min_col, max_col = size, -1
    
    for i, row in enumerate(matrix):
        for j, char in enumerate(row):
            if char != ' ':
                min_row = min(min_row, i)
                max_row = max(max_row, i)
                min_col = min(min_col, j)
                max_col = max(max_col, j)
    
    # 如果没有找到字符（全是空格），返回原始矩阵
    if max_row == -1:
        return matrix
    
    # 计算新的居中位置
    char_height = max_row - min_row + 1
    char_width = max_col - min_col + 1
    
    # 创建新的矩阵，将字符居中
    new_matrix = []
    for i in range(size):
        new_row = []
        for j in range(size):
            # 计算在原矩阵中的位置
            orig_i = min_row + (i - (size - char_height) // 2)
            orig_j = min_col + (j - (size - char_width) // 2)
            
            # 检查是否在有效范围内
            if 0 <= orig_i < size and 0 <= orig_j < len(matrix[orig_i]):
                new_row.append(matrix[orig_i][orig_j])
            else:
                new_row.append(' ')
        new_matrix.append(''.join(new_row))
    
    return new_matrix

def create_fallback_matrix(char, size, style):
    """
    创建一个简单的回退点阵，当所有渲染方法都失败时使用
    """
    matrix = []
    # 创建一个简单的矩形框作为占位符
    for i in range(size):
        row = []
        for j in range(size):
            # 只在边缘绘制
            if i == 0 or i == size - 1 or j == 0 or j == size - 1:
                row.append(style)
            else:
                row.append(' ')
        matrix.append(''.join(row))
    return matrix

def print_chinese_name(name, size=20, style='*'):
    """
    改进的打印函数，提供更清晰的边框和更好的视觉效果
    
    参数:
        name: 要打印的中文名字
        size: 点阵大小 (默认20x20)
        style: 显示样式字符 (默认'*')
    """
    # 获取每个字符的点阵数据
    chars_data = []
    for char in name:
        chars_data.append(char_to_matrix(char, size, style))
    
    # 计算边框宽度
    border_width = size * len(name) + 3 * (len(name) + 1)
    
    # 打印标题和边框
    print("\n" + "=" * border_width)
    print(f"{'中文名字点阵':^{border_width}}")
    print("=" * border_width)
    
    # 打印每个字符的点阵
    for i in range(size):
        line = "| "
        for j, char_data in enumerate(chars_data):
            # 确保索引安全
            if i < len(char_data):
                line += char_data[i]
            else:
                line += ' ' * size
            # 在字符之间添加分隔
            if j < len(chars_data) - 1:
                line += " | "
        line += " |"
        print(line)
    
    # 打印底部边框
    print("=" * border_width + "\n")

def main():
    """
    主函数，提供用户交互界面
    """
    print("欢迎使用中文名字点阵打印程序！")
    print("本版本优化了中文字符的显示效果，使用更清晰的渲染方法。")
    
    # 检查PIL库是否安装
    try:
        import PIL
    except ImportError:
        print("\n错误：需要安装PIL/Pillow库来支持中文字符显示。")
        print("请运行命令：pip install pillow")
        return
    
    # 检查并报告字体状态
    font_path = get_font_path()
    if font_path:
        print(f"\n成功找到字体: {os.path.basename(font_path)}")
    else:
        print("\n警告：未找到合适的中文字体，可能影响显示效果。")
    
    # 先演示几个不同大小的示例
    demo_names = ["张", "张明", "王东恒"]
    demo_sizes = [16, 24, 20]
    
    # 只显示第一个示例作为演示
    print(f"\n示例名字 '{demo_names[0]}' 的点阵打印结果 (大小: {demo_sizes[0]}):")
    print_chinese_name(demo_names[0], demo_sizes[0])
    
    # 提示用户输入名字
    name = input("请输入您的中文名字 (输入'q'退出): ")
    
    while name.lower() != 'q':
        if name.strip():
            try:
                # 获取点阵大小
                size_input = input("请输入点阵大小 (推荐: 16-32, 默认20): ")
                if size_input.strip():
                    size = int(size_input)
                    # 设置更合理的大小范围
                    size = max(12, min(40, size))
                else:
                    size = 20  # 默认大小
                
                # 固定使用星号作为样式，这是最清晰的选择
                style = '*'
                
            except ValueError:
                size = 20
                style = '*'
                print("输入无效，使用默认大小20。")
            
            # 打印结果
            print(f"\n您的名字 '{name}' 的点阵打印结果 (大小: {size}):")
            print_chinese_name(name, size, style)
        else:
            print("请输入有效的名字！")
        
        name = input("请输入您的中文名字 (输入'q'退出): ")
    
    # 结束提示
    print("\n感谢使用中文名字点阵打印程序！")
    print("本程序使用优化的渲染算法，提供更清晰的中文字符显示效果。")

if __name__ == "__main__":
    main()